package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.QiNiuTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    // 用于文件上传或者下载
    @Autowired
    private FastFileStorageClient client;

    // 用于获取application中配置的路径
    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private QiNiuTemplate qiNiuTemplate;

    @DubboReference
    private VideoApi videoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference  // 视频点赞和评论都存在Comment表中
    private CommentApi commentApi;

    /**
     * 上传视频
     *
     * @param videoThumbnail 封面图片文件
     * @param videoFile      视频文件
     */
    public void savaVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws Exception {
        if (videoFile.isEmpty() || videoThumbnail.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }
        // 1:将视频上传到FastDFS,获取访问的URL;
        String filename = videoFile.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf(".") + 1);
        // 参数  文件输入流, 文件长度 ,文件后缀 , 元数据
        StorePath path = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), suffix, null);
        String videoUrl = webServer.getWebServerUrl() + path.getFullPath();  // 路径拼接
        // 2:将封面图片上传到七牛云存储上,获取访问的URL;
        String picUrl = qiNiuTemplate.upload(videoThumbnail.getBytes(), videoThumbnail.getOriginalFilename());
        // 3:构建Videos对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        video.setText("每个人心里都有一个死小孩");
        // 4:调用api保存数据
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }
    }


    // 查看视频列表              key的调用规则  =  T("全类名" + 方法  + 路径参数)
    @Cacheable(value = "videos",key = "T(com.tanhua.server.interceptor.UserHolder).getUserId() +'_'+#page+'_'+#pagesize")
    public PageResult queryVideoList(Integer page, Integer pagesize) {
        // 1:从redis中获取推荐数据
        String redisKey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        // 1.1:拿到redisKey对应的值
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        // 2:判断Redis数据是否存在,判断redis中数据是否满足本次分页条数
        List<Video> list = new ArrayList<>();
        int redisPage = 0;
        if (!StringUtils.isEmpty(redisValue)) {
            // 3:如果redis数据存在,根据vid查询数据,进行分页
            String[] values = redisValue.split(",");  // 首先按照逗号进行切割
            // 判断当前页的起始条数是否小于数组总数
            if ((page - 1) * pagesize < values.length) {
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)  // 分页查询
                        .map(e -> Long.valueOf(e))  // 转化为Long类型的数据
                        .collect(Collectors.toList());  // 转化为集合
                // 4: 调用api根据vids集合查询视频数据
                list = videoApi.findVideosByVids(vids);
            }
            redisPage = PageUtil.totalPage(values.length, pagesize);
        }
        // 4:如果redis数据不存在,分页查询视频数据
        if (list.isEmpty()) {
            // page的计算规则, 传入的页码 -- redis 查询的总页数
            list = videoApi.queryVideoList(page - redisPage, pagesize);
        }
        // 5:提取视频列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        // 6:查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        // 7:构建返回值
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo userInfo = map.get(video.getUserId());
            if (userInfo != null) {
                VideoVo vo = VideoVo.init(userInfo, video);
                String key = Constants.FOCUS_USER_KEY + video.getUserId();  // key使用当前用户id拼接
                String hashKey = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key,hashKey)){
                    vo.setHasFocus(1);
                }
                String key1 = Constants.VIDEO_LIKE_HASHKEY + video.getId();
                String hashKey1 = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key1,hashKey1)){
                    vo.setHasFocus(1);
                }
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0L, vos);
    }


    // 关注发布视频的作者    作者id
    public void userFocus(Long followUserId) {
        if (followUserId != UserHolder.getUserId()) {
            // 1:创建userFocus对象
            FocusUser focusUser = new FocusUser();
            focusUser.setUserId(UserHolder.getUserId());
            focusUser.setFollowUserId(followUserId);
            // focusUser.setCreated(System.currentTimeMillis()); 在数据层实现
            // 2:调用api保存
            videoApi.saveFocusUser(focusUser);
            // 3:将关注记录保存到redis中
            String key = Constants.FOCUS_USER_KEY + followUserId;  // key使用当前用户id拼接
            String hashKey = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
            redisTemplate.opsForHash().put(key, hashKey, "1");
        } else {
            throw new BusinessException(ErrorResult.error());
        }
    }


    // 取消关注作者
    public void userUnFocus(Long followUserId) {
        // 1:调用api清除关注信息
        videoApi.deleteUserUnFocus(followUserId,UserHolder.getUserId());
        // 2:同时清除redis中的缓存信息
        String key = Constants.FOCUS_USER_KEY + followUserId;  // key使用当前用户id拼接
        String hashKey = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
    }


    // 视频点赞功能
    public Integer likeVideoCounts(String id) {
        // 1:查询用户是否点赞
        Boolean like = commentApi.hasComment(id,UserHolder.getUserId(), CommentType.LIKE);
        // 2:如果已经点赞,抛出异常
        if (like){   // 用户已点赞,就取消点赞
        //    Integer dislikeVideoComments = dislikeVideoComments(id);
            throw new BusinessException(ErrorResult.error());
        }
        // 3:调用api保存数据到MongoDb层
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(id));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer counts = videoApi.save(comment);
        // 4:将数据保存到Redis当中
        String key = Constants.VIDEO_LIKE_HASHKEY + id;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return counts;
    }

    // 取消视频点赞功能
    public Integer dislikeVideoComments(String videoId) {
        // 1:查询用户是否点赞
        Boolean hasComment = commentApi.hasComment(videoId,UserHolder.getUserId(),CommentType.LIKE);
        // 2:如果未点赞,就抛出异常
        if (!hasComment){
            throw new BusinessException(ErrorResult.error());
        }
        // 3:如果已经点赞,调用api,删除数据,返回点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        Integer count = videoApi.delete(comment);
        // 4:拼接redis的key,删除点赞状态
        String key = Constants.VIDEO_LIKE_HASHKEY + videoId;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }


    // 发布视频评论
    public Integer saveComments(String videoId, String comment) {
        // 1:获取操作用户id
        Long userId = UserHolder.getUserId();
        // 2:构建comment对象
        Comment videoComment = new Comment();
        videoComment.setPublishId(new ObjectId(videoId));
        videoComment.setContent(comment);
        videoComment.setUserId(userId);
        videoComment.setCommentType(CommentType.COMMENT.getType());
        videoComment.setCreated(System.currentTimeMillis());
        // 3:调用api进行保存
        Integer counts = videoApi.save(videoComment);
        return counts;
    }

    // 分页查询评论列表
    public PageResult findComments(Integer page, Integer pagesize, String videoId) {
        // 1:根据视频id分页查询评论列表
        List<Comment> list = videoApi.findVideoComments(videoId,CommentType.COMMENT,page,pagesize);
        // 2:判断List集合(评论)是否存在
        if (CollUtil.isEmpty(list)){
            return new PageResult();
        }
        // 3:提取出所有的评论人的id,查询出用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        // 4:构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            CommentVo vo = CommentVo.init(userInfo,comment);
            vos.add(vo);
        }
        // 5:构造返回值
        return new PageResult(page,pagesize,0L,vos);
    }

    // 视频评论点赞功能
    public Integer commentsLike(String commentsId) {
        // 1:查询用户是否已经点赞
        Boolean comment = commentApi.hasComment(commentsId, UserHolder.getUserId(), CommentType.LIKE);
        // 2:如果已经点赞,抛出异常
        if (comment){
            throw new BusinessException(ErrorResult.error());
        }
        // 3:如果没有进行点赞,构建数据,调用api进行保存
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(commentsId));
        comment1.setCommentType(CommentType.LIKE.getType());
        comment1.setUserId(UserHolder.getUserId());
        comment1.setCreated(System.currentTimeMillis());
        Integer countsComment = commentApi.saveCommentsLike(comment1);

        // 4:将数据保存到redis中
        String key = Constants.COMMENT_LIKE_ + commentsId;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return countsComment;
    }

    // 视频评论点赞取消功能
    public Integer disCommentsLike(String commentsId) {
        // 1:查询用户是否点赞
        Boolean comment = commentApi.hasComment(commentsId, UserHolder.getUserId(), CommentType.LIKE);
        // 2:如果没有点赞,抛出异常
        if (!comment){
            throw new BusinessException(ErrorResult.error());
        }
        // 3:如果进行了点赞,构建数据,删除点赞
        Comment disLikeComment = new Comment();
        disLikeComment.setPublishId(new ObjectId(commentsId));
        disLikeComment.setUserId(UserHolder.getUserId());
        disLikeComment.setCommentType(CommentType.LIKE.getType());
        Integer counts = commentApi.deleteCommentLike(disLikeComment);
        // 4:清除redis中的缓存
        String key = Constants.COMMENT_LIKE_ + commentsId;
        String hashKey = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return counts;
    }
}
